package ti.me.longhongbing

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    private val historyFile = "history.txt"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "龙虹兵 2022110325"

        val btnAdd = findViewById<Button>(R.id.btn_add)
        val btnSub = findViewById<Button>(R.id.btn_sub)
        val btnMul = findViewById<Button>(R.id.btn_mul)
        val btnDiv = findViewById<Button>(R.id.btn_div)
        btnAdd.setOnClickListener { calculate("+") }
        btnSub.setOnClickListener { calculate("-") }
        btnMul.setOnClickListener { calculate("×") }
        btnDiv.setOnClickListener { calculate("÷") }
    }

    private fun calculate(operator: String) {
        val et_num1 = findViewById<EditText>(R.id.num1)
        val et_num2 = findViewById<EditText>(R.id.num2)
        val tv_result = findViewById<TextView>(R.id.view_result)
        val num1 = et_num1.text.toString().toDouble()
        val num2 = et_num2.text.toString().toDouble()

        val result = when (operator) {
            "+" -> num1 + num2
            "-" -> num1 - num2
            "×" -> num1 * num2
            "÷" -> num1 / num2
            else -> 0.0
        }
        val history = "$num1 $operator $num2 = $result"
        tv_result.text = history
        saveHistory(history)
    }

    private fun saveHistory(history: String) {
        openFileOutput(historyFile, MODE_APPEND).use {
            it.write((history + "\n").toByteArray())
        }
    }


    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.menu_history -> {
                startActivity(Intent(this, HistoryActivity::class.java))
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}

